package log

import (
	"io"
	"io/ioutil"
	"log"
	"strings"
	"os"
)

var (
	Debug *log.Logger
	Info  *log.Logger
	Warn  *log.Logger
	Err   *log.Logger
)

// InitLogger 初始化Logger
func InitLogger(writer io.Writer, fileLevel string) {
	// 默认关闭所有log
	Info = log.New(ioutil.Discard, "[INFO]", log.Ldate|log.Ltime|log.Lshortfile)
	Debug = log.New(ioutil.Discard, "[DEBUG]", log.Ldate|log.Ltime|log.Lshortfile)
	Warn = log.New(ioutil.Discard, "[WARN]", log.Ldate|log.Ltime|log.Lshortfile)
	Err = log.New(ioutil.Discard, "[ERROR]", log.Ldate|log.Ltime|log.Lshortfile)
	// 初始化日志文件
	fileLevel = strings.ToLower(fileLevel)
	switch fileLevel {
	case "debug":
		Info.SetOutput(writer)
		Debug.SetOutput(writer)
		Warn.SetOutput(writer)
		Err.SetOutput(writer)
	case "warn":
		Warn.SetOutput(writer)
		Err.SetOutput(writer)
	case "err":
		Err.SetOutput(writer)
	default:
		// 默认Info级别
		Info.SetOutput(writer)
		Warn.SetOutput(writer)
		Err.SetOutput(writer)
	}
}

// SetLogFileAndInit 设置输出的日志文件
func SetLogFileAndInit(logFileName string, level string) *os.File {
	f, err := os.OpenFile(logFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		log.Fatal(err)
	}
	// 创建多输出writer
	mw := []io.Writer{f, os.Stdout}
	writer := io.MultiWriter(mw...)
	InitLogger(writer, level)
	return f
}
